// pages/release/release.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        carId:'',
        modalName:null,
        userInfo:{},
        newCar:'',
        vehicleList:[],//识别到的车辆信息
        standardname2HoverIndex:0,
        publishCar:{
            carId:'',
            vin:'',//车架号,
            standardname2:'',//车辆型号
            vehicleId: '',//车型唯一标识，从车架号查询结果中获取
            vehicleName: '',//车型名称，从车架号查询结果中获取
            wholesalePrice: '',//批发价(单位：万元)
            retailPrice: '',//零售价(单位：万元)
            recommendReasons: '', //推荐理由
            province: '请选择',city:'',district:'',//省市区
            licensingTime:'请选择',
            yearlyInspectionTime: '请选择',
            compulsoryInsuranceTime: '请选择',
            mileage:'',//表显里程（单位:万公里）
            carColor:'',//车辆颜色
            effluentStandard: '请选择',//排放标准
            importFlag:'请选择',//合资国产进口
            listPrice:'',//厂商指导价（单位:元）
            levelName:'请选择',//车辆类型
            gearboxType:'请选择',//变速箱类型\
            displacement:'',//排量
            transferNums:'',//过户次数
            carPicList:[],//车辆图片
            imageList:[],//回填组件的图片
        },
        carColor:['白色','灰色','黑色','棕色','银色','红色','橙色','黄色','绿色','蓝色','紫色'],//车辆可选颜色
        effluentStandard:['国六','国五','欧六'],
        importFlag:['合资','进口','国产'],
        levelName:['微型车','小型车','小型SUV','紧凑型SUV','中型SUV','中大型SUV','大型SUV','紧凑型车','中型车','中大型车','大型车','跑车','MPV','微面','微卡','轻客','低端皮卡','高端皮卡','紧凑型MPV'],
        gearboxType:['手动变速箱','手自一体自动变速箱','CVT无级变速箱','CVT带挡位的变速箱','双离合变速箱','AMT','序列变速箱'],
        canSub: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    doNothing(){},
    onLoad: function (options) {
        // 必须一个车辆的ID
        if(undefined != options.cid){
            let self = this;
            this.setData({
                'carId': options.cid
            },()=>{
                self.InitUserStatus();
            })
            wx.enableAlertBeforeUnload({
                message: "确定要放弃当前填写内容嘛？",
                success: function (res) {
                },
                fail: function (errMsg) {
                },
            });
        }else{
            app.showNoAuthOrNoGrant('未找到您要查看的车辆哦~');
        }
    },
    // 检查一下登录状态。
    async InitUserStatus(){
        app.showLoading("获取用户信息");
        await app.checkToken();
        this.InitUserInfo();
        wx.hideLoading();
    },
    InitUserInfo(){
        this.setData({
            'userInfo': app.globalData.userInfo
        });
        // 加载车辆信息。
        this.carManageDetail();
    },
    carManageDetail(){
        app.sHttp.carManageDetail(this.data.carId).then(res =>{
            res.result.imageList = [];
            res.result.carPicList.forEach(item =>{
                res.result.imageList.push(item.picUrl);
            });
            if(res.result.listPrice){
                res.result.listPrice = (res.result.listPrice/10000).toFixed(2);
            }
            if(res.result.mileage){
                res.result.mileage = res.result.mileage.toFixed(2);
            }
            if(res.result.transferNums){
                res.result.transferNums = res.result.transferNums.toFixed(0);
            }
            this.setData({
                'publishCar': res.result
            });
            this.validSubParams();
        },err=>{
            app.error(err.msg);
        })
    },
    // 上牌时间变化
    DateChange(e){
        let publishCar = this.data.publishCar;
        publishCar[e.currentTarget.dataset.item] = e.detail.value;
        this.setData({
            'publishCar': publishCar
        })
        this.validSubParams();
    },
    RegionChange: function(e) {
        this.setData({
            'publishCar.province': e.detail.value[0],
            'publishCar.city': e.detail.value[1],
            'publishCar.district': e.detail.value[2]
        });
        this.validSubParams();
    },
    carVinList(){
        if ('' == this.data.publishCar.vin) {
            app.alert('车架号必须填写哦');
            return;
        }
        // 进行查询车架操作
        app.sHttp.carVinList({vin:this.data.publishCar.vin}).then(res =>{
            if(res.vehicleList.length == 1){
                this.setData({
                    'standardname2HoverIndex': 0,
                    'vehicleList': res.vehicleList
                })
                this.okImSure();
            }else{
                this.setData({
                    'vehicleList': res.vehicleList,
                    'modalName':'confirmStandardname2'
                })
            }
        },err=>{
            app.error(err.msg);
        })
    },
    carVinRefreshList(){
        if ('' == this.data.publishCar.vin) {
            app.alert('车架号必须填写哦');
            return;
        }
        // 进行查询车架操作
        app.sHttp.carVinRefreshList({vin:this.data.publishCar.vin}).then(res =>{
            if(res.vehicleList.length == 1){
                this.setData({
                    'standardname2HoverIndex': 0,
                    'vehicleList': res.vehicleList
                })
                this.okImSure();
            }else{
                this.setData({
                    'vehicleList': res.vehicleList,
                    'modalName':'confirmStandardname2'
                })
            }
        },err=>{
            app.error(err.msg);
        })
    },
    thatSIt(e){
        this.setData({
            'standardname2HoverIndex': e.currentTarget.dataset.idx
        })
    },
    okImSure(){
        if (null == this.data.standardname2HoverIndex) {
            app.alert('请选择您确认的车型哦~');
            return;
        }
        app.showLoading('正在确认');
        let sureCar = this.data.vehicleList[this.data.standardname2HoverIndex];
        let publishCar = this.data.publishCar;
        // 回填对应的信息
        for (const key in sureCar) {
            if (Object.hasOwnProperty.call(sureCar, key)) {
                if(key == 'listPrice'){
                    sureCar[key] = (sureCar[key]/10000).toFixed(2)
                }
                publishCar[key] = sureCar[key];
            }
        };
        this.hideModal();
        this.setData({
            'publishCar':publishCar,
            'vehicleList':[]
        });
        this.validSubParams();
        wx.hideLoading();
    },
    submitCar(){
        if (this.validSubParams()) {
            // 验证是否上传了图片.
        let self = this;
        let carPicListUpload = this.selectComponent('#imgDrag');
        carPicListUpload.uploadFiles('carArchives',0,true).then(res=>{
            if (0 == res.length) {
                app.alert('请上传车辆实拍照片');
            }else{
                // 组装用户提交参数,
                let publishCar = app.deepCopy(self.data.publishCar);
                publishCar.carPicList = [];
                res.forEach(element => {
                    publishCar.carPicList.push({picUrl: element.originalUrl});
                });
                delete publishCar.imageList;
                // 将其他的picker参数进行组装   carColor effluentStandard  importFlag levelName gearboxType
                // 判断这些参数的类型.
                let needChangePicker = ['effluentStandard','importFlag','levelName','gearboxType'];
                needChangePicker.forEach(element => {
                    if(Number(publishCar[element]) >= 0){
                        publishCar[element] = Number(publishCar[element]);
                        if (publishCar[element] < self.data[element].length) {
                            publishCar[element] = self.data[element][publishCar[element]];
                        }
                    }
                });
                let _this = self;
                publishCar.listPrice = (publishCar.listPrice*10000).toFixed(2);
                app.sHttp.carManageModify(publishCar).then(res => {
                    // 展示一个发布成功的窗口,因为会返回一个carId
                    if (undefined != res.carId && null != res.carId) {
                        _this.setData({
                            'newCar': res.carId
                        })
                    }
                    let self = this;
                    wx.showModal({
                        title: '修改完成',
                        content: '您的车辆信息修改成功',
                        confirmText:'我知道了',
                        cancelText:'前往查看',
                        showCancel: undefined != res.carId && null != res.carId,
                        success (res) {
                          if (res.confirm) {
                            self.BackPage();
                          } else if (res.cancel) {
                            self.seeNewCar();
                          }
                        }
                      })
                },err =>{
                   app.error(err.msg||err);
                })
            }
        },err=>{
         app.error(err.msg||err);
        });
        }else{
            app.alert('请填写完整信息后发布');
        }
    },
    showModal(e) {
        this.setData({
            modalName: e.currentTarget.dataset.target
        })
    },
    hideModal(e) {
        this.setData({
            modalName: null,
            ocrResult:{}
        })
    },
    openScan(e){
        this.setData({
            'cardType': e.currentTarget.dataset.cardtype,
            'showScan': true,
            'modalName': null
        })
    },
    closeScan(){
        this.setData({
            'cardType': 0,
            'showScan': false
        })
    },
    publishCarInput(e){
        let publishCar = this.data.publishCar;
        publishCar[e.currentTarget.dataset.name] = e.detail.value;
        this.setData({
            'publishCar':publishCar
        });
        this.validSubParams();
    },
    validSubParams(){
        let yuan = {
            vin:'',//车架号,
            vehicleId: '',//车型唯一标识，从车架号查询结果中获取
            vehicleName: '',//车型名称，从车架号查询结果中获取
            wholesalePrice: '',//批发价(单位：万元)
            retailPrice: '',//零售价(单位：万元)
            recommendReasons: '', //推荐理由
            province: '请选择',city:'',district:'',//省市区
            licensingTime:'请选择',
            yearlyInspectionTime: '请选择',
            compulsoryInsuranceTime: '请选择',
            mileage:'',//表显里程（单位:万公里）
            carColor:'请选择',//车辆颜色
            effluentStandard: '请选择',//排放标准
            importFlag:'请选择',//合资国产进口
            listPrice:'',//厂商指导价（单位:元）
            levelName:'请选择',//车辆类型
            gearboxType:'请选择',//变速箱类型
            displacement:'',//排量
            transferNums:'',//过户次数
        };
        let publishCar = this.data.publishCar;
        let canSub = true;
        for (const key in yuan) {
            if (Object.hasOwnProperty.call(publishCar, key) && Object.hasOwnProperty.call(yuan, key)) {
                if (yuan[key] == publishCar[key]) {
                    canSub = false;
                }
            }
            if (Object.hasOwnProperty.call(yuan, key) && !Object.hasOwnProperty.call(publishCar, key)) {
                canSub = false;
            }
        };
        this.setData({
            'canSub': canSub
        });
        return canSub;
    },
    BackPage() {
        wx.disableAlertBeforeUnload({
            success: function (res) {
            },
            fail: function (errMsg) {
            },
        });
      var that = this;
      wx.navigateBack({
        delta: 1,
        fail: function(){
          that.toHome();
        }
      });
    },
    toHome(){
        wx.disableAlertBeforeUnload({
            success: function (res) {
            },
            fail: function (errMsg) {
            },
        });
      wx.reLaunch({
        url: '/pages/home/home',
      })
    },
    seeNewCar(){
        wx.disableAlertBeforeUnload({
            success: function (res) {
            },
            fail: function (errMsg) {
            },
        });
        wx.redirectTo({
          url: '/pages/card/card?cid='+this.data.newCar,
        })
    },
})